package pers.lonestar.framework.utils.support.read;

import java.util.Arrays;
import java.util.List;

import pers.lonestar.framework.utils.support.analysis.analyser.ExcelAnalyser;
import pers.lonestar.framework.utils.support.analysis.analyser.ExcelAnalyserImpl;
import pers.lonestar.framework.utils.support.contexts.XlsxReadContext;
import pers.lonestar.framework.utils.support.metadata.read.ReadSheet;
import pers.lonestar.framework.utils.support.metadata.read.ReadWorkbook;
import reactor.core.publisher.Flux;

public class ExcelReader {
    private final ExcelAnalyser excelAnalyser;
    private final XlsxReadContext xlsxReadContext;

    public ExcelReader(ReadWorkbook readWorkbook) {
        xlsxReadContext = new XlsxReadContext();
        xlsxReadContext.setReadWorkbook(readWorkbook);
        excelAnalyser = new ExcelAnalyserImpl(xlsxReadContext);
    }

    public Flux<?> read(ReadSheet... readSheet) {
        return read(Arrays.asList(readSheet));
    }

    public Flux<?> read(List<ReadSheet> readSheetList) {
        return Flux.create(fluxSink -> {
            xlsxReadContext.setFluxSink(fluxSink);
            excelAnalyser.analysis(readSheetList);
            fluxSink.complete();
        });
    }

    /**
     * 正常解析完成后调用，关闭所有IO或删除临时文件
     */
    public void finish() {
        excelAnalyser.finish();
    }
}
